<?php
namespace app\common\model;
use think\model\concern\SoftDelete;
class Article extends \think\Model
{
    protected $resultSetType = 'collection';
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    //发布人信息
    public function accountInfo(){
        return $this -> hasOne('Account','id','account_id');
    }
    //文章的新增和更新
    public function inserts($login){
        $data = input('param.');
        $validate = validate($this -> name);
        if($data['id']){
            $scenc = 'update';
        }else{
            $scenc = 'upload';
        }
        $result = $validate->scene($scenc)->check($data);
        if(true !== $result){
            return [
                'message' => $validate->getError()
            ];
        }
        //当前自己所处的公司
        $map[] = ['b_id','eq',$login['id']];
        $allAccount = \app\common\model\Record::where($map) -> column('a_id');
        while (!empty($a_id = \app\common\model\Record::where($map)->column('a_id'))){
            $map = [];
            $allAccount = array_unique(array_filter(array_merge($allAccount,$a_id)));
            $map[] = ['b_id','in',$a_id];
        }
        $mapin[] = ['a_id','eq',1];
        $account = \app\common\model\Record::where('a_id','eq',1) -> column('b_id');
        $repeat_arr = array_intersect ($allAccount, $account);
        //保存当前数据
        $datainfo['account_id'] = $login['id'];
        $datainfo['title'] = $data['title'];
        $datainfo['text'] = $data['text'];
        $datainfo['target'] = $data['target'];
        if($repeat_arr[0]){
            $datainfo['company'] = $repeat_arr[0];
        }
        $datainfo['date'] = time();
        if(!$data['id']) {
            $datainfo['img'] = trim($data['img']);
            $datainfo['files'] = trim($data['files']);
            $re = \app\common\model\Article::create($datainfo);
            return [
                'code' => '1',
                'message' => '新增成功',
                'id' => $re -> id
            ];
        }else{
            $re = \app\common\model\Article::where('id',$data['id']) -> find();
            $array = $re['img'].','.$data['img'];
            $datainfo['img'] = trim($array,',');
            $array1 = $re['files'].','.$data['files'];
            $datainfo['files'] = trim($array1,',');
            \app\common\model\Article::where('id',$data['id']) -> update($datainfo);
            $result = \app\common\model\Article::where('id',$data['id']) -> find();
            return [
                'code' => '1',
                'message' => '更新成功',
                'id' => $data['id'],
            ];
        }
    }
    //删除当前文件夹
    public function deletes(){
        $data = input('param.');
        $result = \app\common\model\Article::destroy($data['id']);
        return [
            'code' => '1',
            'message' => '删除成功',
            'id' => $re -> id
        ];;
    }
}